package com.alan.boot.mongo.controller;

import com.alan.boot.mongo.lock.DistributionLockService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author yaoyunqing
 * Created on 2020/04/22
 */
@RestController
public class LockController {
    @Resource
    private DistributionLockService lockService;
    private AtomicLong count = new AtomicLong(0);

    // ab -n 1000 -c 20 http://localhost:8080/getLock/count_lock
    @GetMapping("/getLock/{key}")
    public String getLock(@PathVariable String key) {
        final boolean success = lockService.getLock(key, 3);
        if (success) {
            try {
                count.incrementAndGet();
            } finally {
                lockService.releaseLock(key);
            }

        }
        return success ? "Success to get lock." : "Fail to get lock.";
    }

    @GetMapping("/count")
    public Long count() {
        return count.get();
    }


}
